# 反馈API
from django.http import JsonResponse
from django import forms
from web.models import Feedback, Users, FeedbackImage
from django.forms.models import model_to_dict
from web.apis import tools
from django.views.decorators.csrf import csrf_exempt
from datetime import datetime

# 反馈表单
class FeedbackForm(forms.ModelForm):
    class Meta:
        model = Feedback
        fields = ['feedback_content', 'feedback_user', 'feedback_type']

# 反馈图片表单
class FeedbackImageForm(forms.ModelForm):
    class Meta:
        model = FeedbackImage
        fields = ['feedback', 'image', 'image_type']
    
    def clean_feedback(self):
        feedback = self.cleaned_data.get('feedback')
        if isinstance(feedback, (int, str)):
            try:
                return Feedback.objects.get(feedback_id=feedback)
            except Feedback.DoesNotExist:
                raise forms.ValidationError("反馈不存在")
        return feedback

# 创建反馈
@csrf_exempt
def create_feedback(request):
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                feedback = form.instance
                feedback_dict = model_to_dict(feedback)
                feedback_dict['feedback_user'] = feedback.feedback_user.username
                feedback_dict['feedback_type'] = feedback.get_feedback_type_display()
                feedback_dict['feedback_status'] = feedback.get_feedback_status_display()
                feedback_dict['create_time'] = feedback.create_time.strftime('%Y-%m-%d %H:%M:%S')
                feedback_dict['update_time'] = feedback.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg="反馈创建成功", data=feedback_dict))
            except Exception as e:
                return JsonResponse(tools.ReturnData(code=400, msg=f'保存反馈失败: {str(e)}'))
        else:
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f'{error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg="请使用POST方法"))

# 获取反馈列表
@csrf_exempt
def get_feedback_list(request):
    if request.method == 'GET':
        try:
            feedbacks = Feedback.objects.all().order_by('-create_time')
            feedback_list = []
            for fb in feedbacks:
                fb_dict = model_to_dict(fb)
                fb_dict['feedback_user'] = fb.feedback_user.username
                fb_dict['feedback_type'] = fb.get_feedback_type_display()
                fb_dict['feedback_status'] = fb.get_feedback_status_display()
                if fb.feedback_status == 2:
                    fb_dict['feedback_reply'] = fb.feedback_reply
                    fb_dict['feedback_reply_time'] = fb.feedback_reply_time.strftime('%Y-%m-%d %H:%M:%S')
                    fb_dict['feedback_reply_user'] = fb.feedback_reply_user.username
                fb_dict['create_time'] = fb.create_time.strftime('%Y-%m-%d %H:%M:%S')
                fb_dict['update_time'] = fb.update_time.strftime('%Y-%m-%d %H:%M:%S')
                
                # 获取反馈图片
                images = FeedbackImage.objects.filter(feedback=fb_dict['feedback_id'])
                image_list = []
                for image in images:
                    image_dict = model_to_dict(image)
                    image_dict['image'] = image.image.url
                    image_dict['create_time'] = image.create_time.strftime('%Y-%m-%d %H:%M:%S')
                    image_dict['update_time'] = image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    image_list.append(image_dict)
                fb_dict['images'] = image_list
                
                feedback_list.append(fb_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取反馈列表成功', data=feedback_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取反馈列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg='请使用GET方法'))

# 获取单个反馈
@csrf_exempt
def get_feedback(request, feedback_id):
    if request.method == 'GET':
        try:
            fb = Feedback.objects.filter(feedback_id=feedback_id).first()
            if not fb:
                return JsonResponse(tools.ReturnData(code=400, msg='反馈不存在'))
            fb_dict = model_to_dict(fb)
            fb_dict['feedback_user'] = fb.feedback_user.username
            fb_dict['feedback_type'] = fb.get_feedback_type_display()
            fb_dict['feedback_status'] = fb.get_feedback_status_display()
            fb_dict['create_time'] = fb.create_time.strftime('%Y-%m-%d %H:%M:%S')
            fb_dict['update_time'] = fb.update_time.strftime('%Y-%m-%d %H:%M:%S')
            if fb.feedback_status == 2:
                fb_dict['feedback_reply'] = fb.feedback_reply
                fb_dict['feedback_reply_time'] = fb.feedback_reply_time.strftime('%Y-%m-%d %H:%M:%S')
                fb_dict['feedback_reply_user'] = fb.feedback_reply_user.username
            # 获取反馈图片
            images = FeedbackImage.objects.filter(feedback=fb)
            image_list = []
            for image in images:        
                image_dict = model_to_dict(image)
                image_dict['image'] = image.image.url
                image_dict['create_time'] = image.create_time.strftime('%Y-%m-%d %H:%M:%S')
                image_dict['update_time'] = image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                image_list.append(image_dict)
            fb_dict['images'] = image_list
            
            return JsonResponse(tools.ReturnData(code=200, msg='获取反馈成功', data=fb_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取反馈失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg='请使用GET方法'))

# 更新反馈
@csrf_exempt
def update_feedback(request, feedback_id):
    if request.method == 'POST':
        try:
            fb = Feedback.objects.filter(feedback_id=feedback_id).first()
            if not fb:
                return JsonResponse(tools.ReturnData(code=400, msg='反馈不存在'))
            
            if fb.feedback_status == 2:
                return JsonResponse(tools.ReturnData(code=400, msg='反馈已回复，无法修改'))
            
            fb.feedback_reply = request.POST.get('feedback_reply')
            fb.feedback_reply_time = datetime.now()
            fb.feedback_status = 2
            fb.feedback_reply_user = Users.objects.filter(id=request.POST.get('feedback_reply_user')).first()
            fb.update_time = datetime.now()
            fb.save()
            fb_dict = model_to_dict(fb)
            fb_dict['feedback_user'] = fb.feedback_user.username
            fb_dict['feedback_type'] = fb.get_feedback_type_display()
            fb_dict['feedback_status'] = fb.get_feedback_status_display()
            fb_dict['feedback_reply'] = fb.feedback_reply
            fb_dict['feedback_reply_time'] = fb.feedback_reply_time.strftime('%Y-%m-%d %H:%M:%S')
            fb_dict['feedback_reply_user'] = fb.feedback_reply_user.username
            fb_dict['create_time'] = fb.create_time.strftime('%Y-%m-%d %H:%M:%S')
            fb_dict['update_time'] = fb.update_time.strftime('%Y-%m-%d %H:%M:%S')
            
            # 获取反馈图片
            images = FeedbackImage.objects.filter(feedback=fb)
            image_list = []
            for image in images:
                image_dict = model_to_dict(image)
                image_dict['image'] = image.image.url
                image_dict['create_time'] = image.create_time.strftime('%Y-%m-%d %H:%M:%S')
                image_dict['update_time'] = image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                image_list.append(image_dict)
            fb_dict['images'] = image_list
            
            return JsonResponse(tools.ReturnData(code=200, msg='更新反馈成功', data=fb_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新反馈失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg='请使用POST方法'))

# 删除反馈
@csrf_exempt
def delete_feedback(request, feedback_id):
    if request.method == 'DELETE':
        try:
            fb = Feedback.objects.filter(feedback_id=feedback_id).first()
            if not fb:
                return JsonResponse(tools.ReturnData(code=400, msg='反馈不存在'))
            fb.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除反馈成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除反馈失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg='请使用DELETE方法'))

# 上传反馈图片
@csrf_exempt
def upload_feedback_image(request, feedback_id):
    if request.method == 'POST':
        try:
            feedback = Feedback.objects.filter(feedback_id=feedback_id).first()
            if not feedback:
                return JsonResponse(tools.ReturnData(code=400, msg='反馈不存在'))
            
            if 'image' not in request.FILES:
                return JsonResponse(tools.ReturnData(code=400, msg='请上传图片'))
            image_type = request.POST.get('image_type')
            # 转换图片类型
            image_type = int(image_type)
            if image_type not in [1, 2]:
                return JsonResponse(tools.ReturnData(code=400, msg='图片类型错误'))
            
            # 使用feedback对象初始化表单
            form = FeedbackImageForm(
                data={'feedback': feedback, 'image_type': image_type},
                files=request.FILES
            )
            
            if form.is_valid():
                form.save()
                image_dict = model_to_dict(form.instance)
                image_dict['image'] = form.instance.image.url
                image_dict['create_time'] = form.instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                image_dict['update_time'] = form.instance.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg='上传反馈图片成功', data=image_dict))
            else:
                error_msg = tools.get_first_error(form)
                return JsonResponse(tools.ReturnData(code=400, msg=f'{error_msg}'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'上传反馈图片失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 删除反馈图片
@csrf_exempt
def delete_feedback_image(request, image_id):
    if request.method == 'DELETE':
        try:
            image = FeedbackImage.objects.filter(id=image_id).first()
            if not image:
                return JsonResponse(tools.ReturnData(code=400, msg='反馈图片不存在'))
            
            image.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除反馈图片成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除反馈图片失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

# 获取反馈图片列表
@csrf_exempt
def get_feedback_images(request, feedback_id):
    if request.method == 'GET':
        try:
            feedback = Feedback.objects.filter(feedback_id=feedback_id).first()
            if not feedback:
                return JsonResponse(tools.ReturnData(code=400, msg='反馈不存在'))
            
            images = FeedbackImage.objects.filter(feedback=feedback)
            image_list = []
            for image in images:
                image_dict = model_to_dict(image)
                image_dict['image'] = image.image.url
                image_dict['create_time'] = image.create_time.strftime('%Y-%m-%d %H:%M:%S')
                image_dict['update_time'] = image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                image_list.append(image_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取反馈图片列表成功', data=image_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取反馈图片列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))


# 获取反馈类型列表
@csrf_exempt
def get_feedback_type_list(request):
    if request.method == 'GET':
        try:
            feedback_types = Feedback.feedback_type_choices
            return JsonResponse(tools.ReturnData(code=200, msg='获取反馈类型列表成功', data=feedback_types))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取反馈类型列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 获取用户反馈列表
@csrf_exempt
def get_user_feedback_list(request):
    if request.method == 'GET':
        try:
            user = request.GET.get('user')
            feedbacks = Feedback.objects.filter(feedback_user=user)
            feedback_list = []
            for fb in feedbacks:
                fb_dict = model_to_dict(fb)
                fb_dict['feedback_user'] = fb.feedback_user.username
                fb_dict['feedback_type'] = fb.get_feedback_type_display()
                fb_dict['feedback_status'] = fb.get_feedback_status_display()
                fb_dict['create_time'] = fb.create_time.strftime('%Y-%m-%d %H:%M:%S')
                fb_dict['update_time'] = fb.update_time.strftime('%Y-%m-%d %H:%M:%S')
                if fb.feedback_status == 2:
                    fb_dict['feedback_reply'] = fb.feedback_reply
                    fb_dict['feedback_reply_time'] = fb.feedback_reply_time.strftime('%Y-%m-%d %H:%M:%S')
                    fb_dict['feedback_reply_user'] = fb.feedback_reply_user.username
                
                # 图片
                images = FeedbackImage.objects.filter(feedback=fb)
                image_list = []
                for image in images:
                    image_dict = model_to_dict(image)
                    image_dict['image'] = image.image.url
                    image_list.append(image_dict)
                fb_dict['images'] = image_list
                feedback_list.append(fb_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取用户反馈列表成功', data=feedback_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取用户反馈列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))
    
